import { getCategoryList } from '../../api/category'

// 分类模块
export default {
  namespaced: true,
  state: {
    // 分类列表
    categories: [],
    // 选中的分类
    selectedCategory: null,
    // 分类加载状态
    loading: false,
    // 分类错误信息
    error: null
  },
  
  mutations: {
    // 设置分类列表
    SET_CATEGORIES(state, categories) {
      state.categories = categories
    },
    
    // 设置选中的分类
    SET_SELECTED_CATEGORY(state, category) {
      state.selectedCategory = category
    },
    
    // 设置加载状态
    SET_LOADING(state, loading) {
      state.loading = loading
    },
    
    // 设置错误信息
    SET_ERROR(state, error) {
      state.error = error
    },
    
    // 清除错误信息
    CLEAR_ERROR(state) {
      state.error = null
    },
    
    // 添加分类
    ADD_CATEGORY(state, category) {
      state.categories.push(category)
    },
    
    // 更新分类
    UPDATE_CATEGORY(state, updatedCategory) {
      const index = state.categories.findIndex(category => category.id === updatedCategory.id)
      if (index !== -1) {
        state.categories.splice(index, 1, updatedCategory)
      }
    },
    
    // 删除分类
    REMOVE_CATEGORY(state, categoryId) {
      state.categories = state.categories.filter(category => category.id !== categoryId)
    }
  },
  
  actions: {
    // 获取分类列表
    async fetchCategories({ commit, rootDispatch }) {
      try {
        rootDispatch('showLoading')
        commit('CLEAR_ERROR')
        const response = await getCategoryList()
        commit('SET_CATEGORIES', response.data || [])
        return response.data || []
      } catch (error) {
        const errorMsg = error.response?.data?.message || '获取分类列表失败'
        commit('SET_ERROR', errorMsg)
        rootDispatch('showError', errorMsg)
        return []
      } finally {
        rootDispatch('hideLoading')
      }
    },
    
    // 选择分类
    selectCategory({ commit }, category) {
      commit('SET_SELECTED_CATEGORY', category)
    },
    
    // 清除选中的分类
    clearSelectedCategory({ commit }) {
      commit('SET_SELECTED_CATEGORY', null)
    }
  },
  
  getters: {
    // 获取分类列表
    categories: state => state.categories,
    
    // 获取选中的分类
    selectedCategory: state => state.selectedCategory,
    
    // 分类加载状态
    isLoading: state => state.loading,
    
    // 分类错误信息
    error: state => state.error,
    
    // 根据ID获取分类
    getCategoryById: state => id => {
      return state.categories.find(category => category.id === id)
    },
    
    // 获取分类名称
    getCategoryNameById: state => id => {
      const category = state.categories.find(cat => cat.id === id)
      return category ? category.name : '未知分类'
    },
    
    // 分类是否存在
    categoryExists: state => id => {
      return state.categories.some(category => category.id === id)
    }
  }
}